package com.cimp.websocket;

import com.cimp.domain.tools.UpgradeParam;
import com.cimp.domain.tools.UpgradeResult;
import com.cimp.service.tools.ToolsService;
import com.cimp.domain.tools.SvnConfig;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.socket.*;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * [简要描述]:
 * [详细描述]:
 *
 * @author huojinhao
 * @date 2018/11/14
 */
public class UpgradeHandlerProcessor extends TextWebSocketHandler {

    @Resource
    private ToolsService toolsService;

    @Resource
    private SvnConfig svnConfig;

    private static CopyOnWriteArraySet<WebSocketSession> sessionList = new CopyOnWriteArraySet<>();

    /**
     * 发送消息
     * @param result
     */
    public static void sendMessage(UpgradeResult result){
        JSONObject jsonObject = JSONObject.fromObject(result);
        for (WebSocketSession session : sessionList) {
            if (session.isOpen()) {
                try {
                    session.sendMessage(new TextMessage(jsonObject.toString(), true));
                } catch (IOException e) {
                    sessionList.remove(session);
                }
            }
        }
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        try {
            sessionList.add(session);
            UpgradeParam upgradeParam = toolsService.getUpgradeParam();
            JSONObject jsonObject = JSONObject.fromObject(upgradeParam);
            sendMessage(UpgradeResult.init(jsonObject.toString()));
        } catch (Exception e) {
            sendMessage(UpgradeResult.error(e.getMessage()));
        }

    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        try{
            JSONObject jsonObject = JSONObject.fromObject(message.getPayload());
            UpgradeParam param = (UpgradeParam)JSONObject.toBean(jsonObject,UpgradeParam.class);
            toolsService.upgrade(param);
        }catch (Exception e){
            sendMessage(UpgradeResult.error(e.getMessage()));
        }
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        sessionList.remove(session);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        sessionList.remove(session);
    }
}
